<template>
  <div class="baidu-map-selector">
    <el-input
      v-model="address"
      placeholder="请选择地址"
      readonly
      @click="showMapDialog = true"
    >
      <template #append>
        <el-button @click="showMapDialog = true">📍</el-button>
      </template>
    </el-input>

    <!-- 百度地图选择对话框 -->
    <el-dialog
      v-model="showMapDialog"
      title="选择地址"
      width="80%"
      :before-close="handleClose"
    >
      <div class="map-container">
        <div class="search-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入地址关键词"
            style="width: 300px; margin-right: 10px;"
            @keyup.enter="searchAddress"
          >
            <template #append>
              <el-button @click="searchAddress">搜索</el-button>
            </template>
          </el-input>
          <el-button type="primary" @click="confirmLocation" :disabled="!selectedLocation">
            确认选择
          </el-button>
        </div>
        
        <div id="baidu-map" class="map-content"></div>
        
        <div class="location-info" v-if="selectedLocation">
          <h4>已选择位置：</h4>
          <p><strong>地址：</strong>{{ selectedLocation.address }}</p>
          <p><strong>经度：</strong>{{ selectedLocation.lng }}</p>
          <p><strong>纬度：</strong>{{ selectedLocation.lat }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { getBaiduMapApiKey } from '@/config/baiduMap'

// 声明全局变量
declare global {
  interface Window {
    BMap: any
    initBaiduMap: () => void
  }
}

// Props
const props = defineProps<{
  modelValue: string
}>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: string]
  'location-selected': [location: { address: string; lng: number; lat: number }]
}>()

// 响应式数据
const showMapDialog = ref(false)
const searchKeyword = ref('')
const address = ref(props.modelValue || '')
const selectedLocation = ref<{ address: string; lng: number; lat: number } | null>(null)

// 百度地图相关（懒加载）
let map: any = null
let geocoder: any = null
let marker: any = null
let mapLoaded = false // 是否已加载百度地图脚本

// 监听地址变化
watch(() => props.modelValue, (newValue) => {
  address.value = newValue || ''
})

// 监听地址变化并同步到父组件
watch(address, (newValue) => {
  emit('update:modelValue', newValue)
})

// 初始化百度地图
const initMap = () => {
  // 如果已初始化，直接返回
  if (map) return
  
  // 检查百度地图API是否已加载
  if (!mapLoaded && typeof BMap === 'undefined') {
    // 动态加载百度地图API（仅在首次打开对话框时加载）
    const script = document.createElement('script')
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=${getBaiduMapApiKey()}&callback=initBaiduMap`
    script.async = true
    document.head.appendChild(script)
    
    // 定义全局回调函数
    ;(window as any).initBaiduMap = () => {
      mapLoaded = true
      createMap()
    }
  } else {
    // 已加载脚本，直接创建地图
    mapLoaded = true
    createMap()
  }
}

// 创建地图
const createMap = () => {
  try {
    // 创建地图实例（默认显示北京）
    map = new BMap.Map('baidu-map')
    const point = new BMap.Point(116.404, 39.915)
    map.centerAndZoom(point, 12)
    map.enableScrollWheelZoom()
    map.addControl(new BMap.NavigationControl())
    map.addControl(new BMap.ScaleControl())
    map.addControl(new BMap.OverviewMapControl())
    map.addControl(new BMap.MapTypeControl())

    // 创建地址解析器
    geocoder = new BMap.Geocoder()

    // 添加点击事件
    map.addEventListener('click', (e: any) => {
      const point = e.point
      geocoder.getLocation(point, (result: any) => {
        if (result) {
          const address = result.address
          selectedLocation.value = {
            address,
            lng: point.lng,
            lat: point.lat
          }
          
          // 清除之前的标记
          if (marker) {
            map.removeOverlay(marker)
          }
          
          // 添加新标记
          marker = new BMap.Marker(point)
          map.addOverlay(marker)
          
          // 添加信息窗口
          const infoWindow = new BMap.InfoWindow(address)
          marker.addEventListener('click', () => {
            map.openInfoWindow(infoWindow, point)
          })
        }
      })
    })

    ElMessage.success('地图初始化成功')
  } catch (error) {
    console.error('地图初始化失败:', error)
    ElMessage.error('地图初始化失败，请检查百度地图API配置')
  }
}

// 搜索地址
const searchAddress = () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  if (!geocoder) {
    ElMessage.error('地图未初始化完成')
    return
  }

  // 地址解析
  geocoder.getPoint(searchKeyword.value, (point: any) => {
    if (point) {
      map.centerAndZoom(point, 15)
      
      // 清除之前的标记
      if (marker) {
        map.removeOverlay(marker)
      }
      
      // 添加新标记
      marker = new BMap.Marker(point)
      map.addOverlay(marker)
      
      // 获取详细地址
      geocoder.getLocation(point, (result: any) => {
        if (result) {
          const address = result.address
          selectedLocation.value = {
            address,
            lng: point.lng,
            lat: point.lat
          }
          
          // 添加信息窗口
          const infoWindow = new BMap.InfoWindow(address)
          marker.addEventListener('click', () => {
            map.openInfoWindow(infoWindow, point)
          })
          
          ElMessage.success('地址搜索成功')
        }
      })
    } else {
      ElMessage.warning('未找到该地址')
    }
  })
}

// 确认选择位置
const confirmLocation = () => {
  if (selectedLocation.value) {
    address.value = selectedLocation.value.address
    emit('location-selected', selectedLocation.value)
    showMapDialog.value = false
    ElMessage.success('地址选择成功')
  }
}

// 关闭对话框
const handleClose = () => {
  showMapDialog.value = false
  // 重置选择状态
  selectedLocation.value = null
}

// 生命周期
onMounted(() => {
  // 不在挂载时加载地图，改为在打开对话框后懒加载
  watch(showMapDialog, async (visible) => {
    if (visible) {
      await nextTick()
      initMap()
    }
  })
})
</script>

<style scoped>
.baidu-map-selector {
  width: 100%;
}

.map-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 0;
}

.map-content {
  width: 100%;
  height: 500px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.location-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.location-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
}

.location-info p {
  margin: 5px 0;
  color: #606266;
}
</style>

 